/*
 * itm_stream.c
 *
 *  Created on: 2021-08-05
 *      Author: chenss
 */

#include "stream/itm_stream.h"
#include "message_queue.h"

static int _Put(void *stream, unsigned char b)
{
    ItmStream_t *itm = stream;
    int channel = itm->userData;

    if (((ITM->TCR & ITM_TCR_ITMENA_Msk) != 0UL) &&      /* ITM enabled */
        ((ITM->TER & (1UL << channel)  ) != 0UL)   )     /* ITM Port #channel enabled */
    {
        while(ITM->PORT[channel].u32 == 0UL)
        {
            __NOP();
        }

        ITM->PORT[channel].u8 = b;
    }

    return 1;
}

/**
 * 初始化ITM stream
 * @param itm ITM stream指针
 * @param channel  ITM通道:0~31
 */
int ItmStream_Init(ItmStream_t *itm, int channel)
{
    return IoStream_InitWithoutBuffer(itm, _Put, NULL, NULL, channel);
}

#if 0
static ItmStream_t *_receiver = NULL;

void ItmStream_SetReceiver(ItmStream_t *itm)
{
    _receiver = itm;
}

void ItmStream_Receive(void)
{
    int32_t ret;
    char c;
    Stream_t *stream;

    if(_receiver == NULL)
    {
        return;
    }

    ret = ITM_ReceiveChar();
    if(ret == -1)
    {
        return;
    }

    c = (char)ret;
    IoStream_OnRx(_receiver, c);
    if(c == '\n')
    {
        stream = & _receiver->stream;
        MsgQueue_Send(MsgQueue_Id_ShellLineIn, & stream, sizeof(stream));
    }
}
#endif
